<template>
  <view class="ai-chat-container">
    <!-- 消息列表区域 -->
    <scroll-view 
      class="chat-message-list" 
      scroll-y 
      :scroll-with-animation="true"
      :scroll-top="scrollTop"
      @scroll="onScroll"
    >
      <!-- 系统提示 -->
      <view class="system-message">
        您好！我是 AI 助手，有什么可以帮助您的？
      </view>

      <!-- 消息项 -->
      <view 
        v-for="(msg, index) in messageList" 
        :key="index" 
        class="message-item"
        :class="{ 'user-message': msg.role === 'user', 'ai-message': msg.role === 'ai' }"
      >
        <!-- 头像 -->
        <view class="avatar">
<!--          <uni-icons -->
<!--            :type="msg.role === 'user' ? 'person' : 'robot'" -->
<!--            size="36" -->
<!--            :color="msg.role === 'user' ? '#409eff' : '#67c23a'"-->
<!--          ></uni-icons>-->
          <image
              :src="msg.role === 'user' ? userAvatar : robotAvatar"
              mode="widthFix"
             class="avatar-img"
          ></image>
        </view>
        
        <!-- 消息内容 -->
        <view class="message-content">
          <view class="content-text">{{ msg.content }}</view>
          <view class="content-time">{{ formatTime(msg.timestamp) }}</view>
        </view>
      </view>

      <!-- 加载中状态 -->
      <view v-if="isLoading" class="loading-item">
        <view class="avatar">
          <uni-icons type="robot" size="36" color="#67c23a"></uni-icons>
        </view>
        <view class="loading-content">
          <view class="loading-dot"></view>
          <view class="loading-dot"></view>
          <view class="loading-dot"></view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="chat-input-area">
      <textarea 
        class="input-box"
        v-model="inputContent"
        placeholder="请输入您的问题..."
        @confirm="sendMessage"
        :autosize="{ maxHeight: 120, minHeight: 40 }"
      ></textarea>
      <button 
        class="send-btn" 
        @click="sendMessage"
        :disabled="!inputContent.trim() || isLoading"
      >
        <uni-icons type="send" size="18" color="#fff"></uni-icons>
        发送
      </button>
    </view>
  </view>
</template>

<script>
import {sendMessage} from "@/api/ai/ai";

export default {
  data() {
    return {
      messageList: [], // 消息列表
      inputContent: '', // 输入内容
      isLoading: false, // 加载状态
      scrollTop: 0, // 滚动位置
      isDark: false, // 深色模式开关
      lastScrollTop: 0, // 记录上次滚动位置
      robotAvatar: 'http://119.29.117.29:9000/nalang/images/tabbar/AI.png',
      userAvatar: 'http://119.29.117.29:9000/nalang/images/profile.jpg'
    };
  },
  onLoad() {
    // 初始化主题（可从缓存读取）
    this.isDark = uni.getStorageSync('aiChatDarkMode') || false;
    // this.setPageTheme();
  },
  watch: {
    // 监听消息列表变化，自动滚动到底部
    messageList() {
      this.$nextTick(() => {
        this.scrollTop = 99999; // 滚动到底部
      });
    },
    // 监听主题变化
    isDark() {
      this.setPageTheme();
      uni.setStorageSync('aiChatDarkMode', this.isDark);
    }
  },
  methods: {
    // 发送消息
   async sendMessage() {
      const content = this.inputContent.trim();
      if (!content) return;

      // 添加用户消息
      this.messageList.push({
        role: 'user',
        content,
        timestamp: new Date().getTime()
      });
      this.inputContent = '';
      this.isLoading = true;
      let params = {
        question: content
      };
      //发送请求
      const {data} =await sendMessage(params)
     console.log( "返回的数据",data)
     this.messageList.push({
       role: 'ai',
       // content: `您刚才说："${content}"。这是一条AI模拟回复，实际项目中会替换为真实的AI接口返回内容。`,
       content: data,
       timestamp: new Date().getTime()
     });
     this.isLoading = false;
      // 模拟AI回复（实际项目中替换为接口请求）
/*      setTimeout(() => {
        this.messageList.push({
          role: 'ai',
          // content: `您刚才说："${content}"。这是一条AI模拟回复，实际项目中会替换为真实的AI接口返回内容。`,
          content: `您刚才说："${content}"。这是一条AI模拟回复，实际项目中会替换为真实的AI接口返回内容。`,
          timestamp: new Date().getTime()
        });
        this.isLoading = false;
      }, 1500);*/
    },

    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    // 滚动事件
    onScroll(e) {
      this.lastScrollTop = e.detail.scrollTop;
    },

    // 返回上一页
    handleBack() {
      uni.navigateBack();
    },

    // 切换主题
    toggleTheme() {
      this.isDark = !this.isDark;
    },

    // 设置页面主题
    setPageTheme() {
      const page = getCurrentPages()[getCurrentPages().length - 1];
      const webview = page.$getAppWebview();
      if (this.isDark) {
        webview.setStyle({ backgroundColor: '#1a1a1a' });
      } else {
        webview.setStyle({ backgroundColor: '#f5f5f5' });
      }
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

/* 深色模式 */
.ai-chat-container.dark {
  background-color: #1a1a1a;
  color: #fff;
}

/* 导航栏 */
.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.dark .chat-header {
  background-color: #2c2c2c;
  border-bottom-color: #333;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.header-left, .header-right {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 消息列表 */
.chat-message-list {
  flex: 1;
  padding: 16px;
  box-sizing: border-box;
}

.system-message {
  text-align: center;
  font-size: 14px;
  color: #888;
  padding: 8px 16px;
  background-color: #eee;
  border-radius: 16px;
  margin: 0 auto 16px;
  max-width: 80%;
}

.dark .system-message {
  background-color: #333;
  color: #aaa;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  max-width: 85%;
}

.user-message {
  flex-direction: row-reverse;
  margin-left: auto;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
}

.dark .avatar {
  background-color: #333;
}

.user-message .avatar {
  margin-right: 0;
  margin-left: 10px;
}

.message-content {
  position: relative;
}

.content-text {
  padding: 12px 16px;
  border-radius: 18px;
  line-height: 1.5;
  font-size: 15px;
}

.ai-message .content-text {
  background-color: #fff;
  border: 1px solid #eee;
}

.user-message .content-text {
  background-color: #409eff;
  color: #fff;
}

.dark .ai-message .content-text {
  background-color: #2c2c2c;
  border-color: #444;
  color: #fff;
}

.content-time {
  font-size: 12px;
  color: #888;
  margin-top: 4px;
  text-align: right;
}

.dark .content-time {
  color: #666;
}

/* 加载状态 */
.loading-item {
  display: flex;
  margin-bottom: 20px;
  max-width: 85%;
}

.loading-content {
  display: flex;
  gap: 6px;
  padding: 12px 16px;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 18px;
}

.dark .loading-content {
  background-color: #2c2c2c;
  border-color: #444;
}

.loading-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #67c23a;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dot:nth-child(1) { animation-delay: -0.32s; }
.loading-dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

/* 输入区域 */
.chat-input-area {
  display: flex;
  padding: 10px 16px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.dark .chat-input-area {
  background-color: #2c2c2c;
  border-top-color: #333;
}

.input-box {
  flex: 1;
  min-height: 40px;
  max-height: 120px;
  padding: 10px 16px;
  border: 1px solid #eee;
  border-radius: 20px;
  font-size: 15px;
  resize: none;
  outline: none;
}

.dark .input-box {
  background-color: #333;
  border-color: #444;
  color: #fff;
}

.send-btn {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: #409eff;
  color: #fff;
  margin-left: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  line-height: 1;
}

.send-btn:disabled {
  background-color: #ccc;
}
/* 头像 容器样式（确保图片居中显示） */
.avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  /* 可根据需要设置容器大小 */
  width: 80rpx;
  height: 80rpx;
}

/* 头像图片样式（统一大小） */
.avatar-img {
  width: 60rpx;  /* 头像宽度 */
  height: 60rpx; /* 头像高度（与宽度一致，确保是圆形/方形） */
  border-radius: 8rpx; /* 可选：添加圆角，更头像更美观 */
}
</style>